<template>
  <div class="ddns-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>动态DNS配置</h3>
          <el-button type="primary" @click="saveConfig" :loading="saving">保存配置</el-button>
        </div>
      </template>
      
      <el-form :model="form" label-position="top" :rules="rules" ref="formRef">
        <el-form-item label="Cloudflare API Token" prop="cloudflare_api_token">
          <el-input v-model="form.cloudflare_api_token" placeholder="请输入您的Cloudflare API Token" clearable>
            <template #prepend>
              <i class="fas fa-key"></i>
            </template>
          </el-input>
          <div class="form-help">从Cloudflare控制面板获取，需要Zone:Read和DNS:Edit权限</div>
        </el-form-item>
        
        <el-divider>域名设置</el-divider>
        
        <el-form-item label="域名列表" prop="domain_names">
          <div v-for="(domain, index) in form.domain_names" :key="index" class="domain-input-group">
            <el-input v-model="form.domain_names[index]" placeholder="例如: example.com">
              <template #prepend>
                <i class="fas fa-globe"></i>
              </template>
              <template #append>
                <el-button @click="removeDomain(index)" :disabled="form.domain_names.length <= 1">
                  <i class="fas fa-trash-alt"></i>
                </el-button>
              </template>
            </el-input>
          </div>
          <el-button type="primary" plain @click="addDomain" class="add-button">
            <i class="fas fa-plus"></i> 添加域名
          </el-button>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检查间隔 (秒)" prop="check_interval">
              <el-input-number v-model="form.check_interval" :min="60" :step="60" class="w-100"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="IP版本" prop="ip_version">
              <el-select v-model="form.ip_version" class="w-100">
                <el-option label="IPv4" value="ipv4"></el-option>
                <el-option label="IPv6" value="ipv6"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider>高级设置</el-divider>
        
        <el-collapse>
          <el-collapse-item title="IPv4 检测服务" name="ipv4_services">
            <div v-for="(service, index) in form.ipv4_services" :key="'ipv4-'+index" class="service-input-group">
              <el-input v-model="form.ipv4_services[index]" placeholder="例如: https://api.ipify.org">
                <template #prepend>
                  <i class="fas fa-link"></i>
                </template>
                <template #append>
                  <el-button @click="removeIPv4Service(index)">
                    <i class="fas fa-trash-alt"></i>
                  </el-button>
                </template>
              </el-input>
            </div>
            <el-button type="primary" plain @click="addIPv4Service" class="add-button">
              <i class="fas fa-plus"></i> 添加IPv4服务
            </el-button>
          </el-collapse-item>
          
          <el-collapse-item title="IPv6 检测服务" name="ipv6_services">
            <div v-for="(service, index) in form.ipv6_services" :key="'ipv6-'+index" class="service-input-group">
              <el-input v-model="form.ipv6_services[index]" placeholder="例如: https://api6.ipify.org">
                <template #prepend>
                  <i class="fas fa-link"></i>
                </template>
                <template #append>
                  <el-button @click="removeIPv6Service(index)">
                    <i class="fas fa-trash-alt"></i>
                  </el-button>
                </template>
              </el-input>
            </div>
            <el-button type="primary" plain @click="addIPv6Service" class="add-button">
              <i class="fas fa-plus"></i> 添加IPv6服务
            </el-button>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import axios from 'axios'

const form = reactive({
  cloudflare_api_token: "",
  domain_names: [""],
  check_interval: 300,
  ip_version: "ipv4",
  ipv4_services: [],
  ipv6_services: []
})

const rules = {
  cloudflare_api_token: [
    { required: true, message: '请输入Cloudflare API Token', trigger: 'blur' }
  ],
  domain_names: [
    { type: 'array', required: true, message: '请至少添加一个域名', trigger: 'change' }
  ],
  check_interval: [
    { required: true, message: '请设置检查间隔', trigger: 'blur' },
    { type: 'number', min: 60, message: '间隔最小为60秒', trigger: 'blur' }
  ],
  ip_version: [
    { required: true, message: '请选择IP版本', trigger: 'change' }
  ]
}

const formRef = ref(null)
const saving = ref(false)

// 加载配置
const loadConfig = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载配置中...',
    background: 'rgba(255, 255, 255, 0.7)'
  })
  
  try {
    const response = await axios.get('/api/ddns/config')
    if (response.data.success) {
      const config = response.data.data
      form.cloudflare_api_token = config.cloudflare_api_token || ""
      form.domain_names = config.domain_names && config.domain_names.length ? config.domain_names : [""]
      form.check_interval = config.check_interval || 300
      form.ip_version = config.ip_version || "ipv4"
      form.ipv4_services = config.ipv4_services || []
      form.ipv6_services = config.ipv6_services || []
    } else {
      ElMessage.error('加载配置失败')
    }
  } catch (error) {
    console.error('加载配置出错:', error)
    ElMessage.error('无法连接到服务器')
  } finally {
    loading.close()
  }
}

// 保存配置
const saveConfig = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请先填写必填项')
      return
    }
    
    saving.value = true
    
    // 清理空域名
    form.domain_names = form.domain_names.filter(domain => domain.trim() !== '')
    if (form.domain_names.length === 0) {
      form.domain_names = [""]
    }
    
    try {
      const response = await axios.post('/api/ddns/config', form)
      if (response.data.success) {
        ElMessage.success('保存成功')
      } else {
        ElMessage.error(response.data.message || '保存失败')
      }
    } catch (error) {
      console.error('保存配置出错:', error)
      ElMessage.error('无法连接到服务器')
    } finally {
      saving.value = false
    }
  })
}

// 域名操作
const addDomain = () => {
  form.domain_names.push("")
}

const removeDomain = (index) => {
  if (form.domain_names.length > 1) {
    form.domain_names.splice(index, 1)
  }
}

// IPv4服务操作
const addIPv4Service = () => {
  form.ipv4_services.push("")
}

const removeIPv4Service = (index) => {
  form.ipv4_services.splice(index, 1)
}

// IPv6服务操作
const addIPv6Service = () => {
  form.ipv6_services.push("")
}

const removeIPv6Service = (index) => {
  form.ipv6_services.splice(index, 1)
}

onMounted(() => {
  loadConfig()
})
</script> 